<template>
  <el-tabs v-model="activeName">
    <el-tab-pane label="批次依赖图示" name="t1">
      <div class="super-flow-demo1">
        <div class="flow-container"
             ref="flowContainer"
             @wheel="mouseWheel($event)"
             @click="flowNodeClick">
          <super-flow
            @toJSON="toJSON"
            ref="superFlow"
            :link-addable="false"
            :link-editable="false"
            :graph-menu="graphMenu"
            :node-menu="nodeMenu"
            :link-menu="linkMenu"
            :link-base-style="linkBaseStyle"
            :link-style="linkStyle"
            :link-desc="linkDesc"
            :node-list="nodeList"
            :link-list="linkList">
            <template v-slot:node="{meta}">
              <div @mouseup="nodeMouseUp" @click="nodeClick"
                   :class="meta.type? `flow-node-${meta.type}`: ''"
                   class="flow-node ellipsis">
                <div class="node-content" :title="meta.name">{{ meta.name }}</div>
              </div>
            </template>
          </super-flow>
        </div>
      </div>

    </el-tab-pane>
    <el-tab-pane label="批次依赖配置">
      <el-table
        :data="dependList"
        border
        v-loading="dataListLoading"
        style="width: 100%;">
        <el-table-column prop="bizCode" label="系统组" header-align="center" align="center"></el-table-column>
        <el-table-column prop="batchCode" label="批次" header-align="center" align="center"></el-table-column>
        <!--<el-table-column prop="dpdonBizCode" label="依赖系统组" header-align="center" align="center"></el-table-column>-->
        <el-table-column prop="dpdonBatchCode" label="依赖批次" header-align="center" align="center">
          <template slot-scope="scope">
            <span v-if="!scope.row.isNew">
                    {{scope.row.dpdonBizCode}}:{{scope.row.dpdonBatchCode}}
                </span>
            <span v-if="scope.row.isNew">
               <el-select v-model="scope.row.dpdonBatchCodeGroup" style="width: 90%; text-align: center; margin-left: 1%">
                 <el-option label="--:--" value="--&&--"></el-option>
                      <template v-for="(item, index) in dependList">
                      <el-option :key="index" v-if="item.batchCode != scope.row.batchCode"
                                 :label="item.bizCode+':'+item.batchCode" :value="item.bizCode+'&&'+item.batchCode"></el-option>
                      </template>
                    </el-select>
                  </span>
          </template>
        </el-table-column>
        <el-table-column prop="enabled" label="启用状态" header-align="center" align="center">
          <template slot-scope="scope">
            <template v-for="(item, index) in dict.Enabled">
              <el-tag v-if="item.value == scope.row.enabled" :type="item.style" style="padding: 0 4px">
                {{item.value}}: {{item.label}}
              </el-tag>
            </template>
          </template>
        </el-table-column>

        <el-table-column label="操作" fixed="right" header-align="center" align="center" width="150">
          <template slot-scope="scope">
            <el-button v-if="!scope.row.isNew" type="text" size="small"
                       @click="modRowNewEntity(scope.$index, scope.row)">修改
            </el-button>
            <el-button v-if="scope.row.isNew" type="text" size="small" @click="cancelDepend(scope.$index, scope.row)">
              C:取消
            </el-button>
            <el-button v-if="scope.row.isNew" type="text" size="small" @click="saveDepends(scope.$index, scope.row)">
              S:保存
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--      <div class="demo-block-control">
              <i class="el-icon-caret-bottom"></i>
              <el-button class="dbsavebtn" type="primary" size="mini" @click="saveDepends"
                         style="float: left; right: 12px; position: absolute; margin: 8px 12px 0 0;">保存依赖
              </el-button>
            </div>-->
      <div style="color: #dd6161; line-height: 42px; font-weight: bold;"> 批次依赖暂时无法使用，配置不生效</div>
    </el-tab-pane>
  </el-tabs>


</template>

<script>
  import SuperFlow from 'vue-super-flow'
  //import 'vue-super-flow/lib/index.css'
  import '../../../../public/css/vue-super-flow-index.css'

  const drawerType = {
    node: 0,
    link: 1
  }

  export default {
    components: {
      SuperFlow
    },
    data() {
      return {
        nodeList: [],
        linkList: [],
        activeName: 't1',
        dependList: [],
        dependListBak: [],
        dataListLoading: false,
        drawerType,
        drawerConf: {},
        dragConf: {
          isDown: true,
          isMove: true,
          offsetTop: 0,
          offsetLeft: 0,
          clientX: 0,
          clientY: 0,
          ele: null,
          info: null
        },
        graphMenu: [],
        nodeMenu: [],
        linkMenu: [],

        linkBaseStyle: {
          color: '#666666', // line 颜色
          hover: '#FF0000', // line hover 的颜色
          textColor: '#666666', // line 描述文字颜色
          textHover: '#FF0000', // line 描述文字 hover 颜色
          font: '14px Arial', // line 描述文字 字体设置 参考 canvas font
          dotted: false, // 是否是虚线
          lineDash: [4, 4], // 虚线时生效，虚线长度和间隔长度
          background: 'rgba(255,255,255,0.6)' // 描述文字背景色
        },
      }
    },
    mounted() {
      this.queryMap();
      this.queryDpdList();
      //document.addEventListener('mousemove', this.docMousemove)
      //document.addEventListener('mouseup', this.docMouseup)
      // this.$once('hook:beforeDestroy', () => {
      //   document.removeEventListener('mousemove', this.docMousemove)
      //   document.removeEventListener('mouseup', this.docMouseup)
      // });
      // 创建连接线
      // this.createLink(this.nodeList[0], this.nodeList[1]);
      // this.createLink(this.nodeList[1], this.nodeList[2]);
      // this.createLink(this.nodeList[1], this.nodeList[3]);
      // this.createLink(this.nodeList[3], this.nodeList[2]);
    },
    methods: {
      // addDepend(){
      //   let lineDb = {
      //     selfType: 'T',
      //     bizCode: '',
      //     batchCode: '',
      //     taskCode: '',
      //     dpdonBizCode: '',
      //     dpdonBatchCode: '',
      //     enabled: 1,
      //     isNew: true,
      //   }
      //   this.dependList.push(lineDb)
      // },
      modRowNewEntity(idx, row) {
        row.isNew = true;
        // 重新赋值，table刷新
        let dataArrTemp = JSON.stringify(this.dependList);
        this.dependList = JSON.parse(dataArrTemp);
      },
      cancelDepend(idx, row) {
        row.isNew = false;
        // 重新赋值，table刷新
        let dataArrTemp = JSON.stringify(this.dependListBak);
        this.dependList = JSON.parse(dataArrTemp);
      },
      saveDepends(idx, row) {
        let saveDepends = [];
        let dpd =  row.dpdonBatchCodeGroup;
        let dpds = dpd.split("&&");
        row.dpdonBizCode = dpds[0];
        row.dpdonBatchCode = dpds[1];
        saveDepends.push(row);
        if (saveDepends.length == 0) {
          return;
        }
        let obj = {
          "depends": saveDepends
        }
        this.getTableList('/api/dependon/add', obj, (data) => {
          this.dataListLoading = false
          if (data.code == '000000' ) {
            this.dependList = [];
            this.queryDpdList(row.bizCode, row.batchCode, "");
            this.queryMap();
          }
        })
      },

      mouseWheel(event) {
        if (event.isTrusted) {
          let zom = this.$refs.flowContainer.style.zoom;
          if (!zom) {
            zom = 100;
          } else if (zom.indexOf('%') > 0) {
            zom = parseInt(zom.substring(0, zom.length - 1));
          }
          if (event.deltaY > 0) {
            if (zom < 40) {
              zom = 40;
            }
            this.$refs.flowContainer.style.zoom = (zom - 2) + "%";
          } else {
            if (zom > 150) {
              zom = 150;
            }
            this.$refs.flowContainer.style.zoom = (zom + 2) + "%";
          }
        }
      },
      queryDpdList() {
        this.dataListLoading = true
        let obj = {
          "selfType": "B",
        }
        this.dependList = []
        this.dependListBak = []
        this.getTableList('/api/dependon/batch-list', obj, (data) => {
          this.dataListLoading = false
          if (data.code == '000000' && data.rows && data.rows.length > 0) {
            this.dependList = data.rows
            this.dependList.forEach(item => {
              item.isNew = false;
            });
            let dataArrTemp = JSON.stringify(this.dependList);
            this.dependListBak = JSON.parse(dataArrTemp);
          }
        });
      },
      queryMap() {
        let maxH = 700;
        this.dataListLoading = true
        this.nodeList = [];
        this.linkList = [];
        let obj = {
          "bizCode": "",
          "batchCode": "",
          "includeChild": false,
        }
        obj = Object.assign(obj, this.searchForm)
        this.getTableList('/api/dependon/batch-map', obj, (data) => {
          this.dataListLoading = false
          if (data.code == '000000') {
            let maxCol = data.maxCol;
            let maxRow = data.maxRow;
            let oneSh = 120;
            if ((oneSh + 40) * maxRow > maxH) {
              oneSh = maxH / maxRow - 40;
            }
            if (data.nodes && data.nodes.length > 0) {
              data.nodes.forEach(node => {
                let one = {
                  id: node.bizCode + node.batchCode + node.taskCode + node.jobCode,
                  coordinate: [(node.x - 1) * 180 + 50, oneSh * (node.y - 1) + 50],
                  width: 130,
                  height: 40,
                  meta: {
                    name: '' + node.name,
                    type: 'B' == node.selfType ? 'start' : 'process'
                  }
                };
                this.nodeList.push(one);
              })
            }
            if (data.links && data.links.length > 0) {
              data.links.forEach(link => {
                let pid = link.dpdonBizCode + link.dpdonBatchCode + link.dpdonTaskCode + link.dpdonJobCode;
                let id = link.bizCode + link.batchCode + link.taskCode + link.jobCode
                this.createLink(pid, id);
              });
            }
          }
        })
      },
      flowNodeClick() {
        // console.log(this.$refs.superFlow.graph)
        // const data = this.$refs.superFlow.toJSON()
        // console.log(data)
      },
      toJSON(data) {
        // console.log(data)
      },
      /**
       * 通过ID创建连线
       * @param {nomber} 连线开始节点id
       * @param {nomber} 连线结束节点id
       */
      createLink(startID, endID) {
        this.linkList.push({
          id: '' + startID + '-' + endID,
          startId: startID,
          endId: endID,
          startAt: [110, 60], // 连线位置,粗略试了一下,第一个是控制左右的(小于等于100在左边开始, 大于100右边开始)
          endAt: [60, 0],
          meta: null,
        })
      },
      linkStyle(link) {
        if (link.meta && link.meta.desc === '1') {
          return {
            color: '#FF00FF',
            hover: '#FF00FF',
            dotted: true
          }
        } else {
          return {}
        }
      },
      linkDesc(link) {
        return link.meta ? link.meta.desc : ''
      },
      nodeMouseUp(evt) {
        evt.preventDefault()
      },
      nodeClick() {
        // console.log(arguments)
      },
      docMousemove({clientX, clientY}) {
        // const conf = this.dragConf
        // if (conf.isMove) {
        //   if(conf.ele ){
        //     conf.ele.style.top = clientY - conf.offsetTop + 'px'
        //     conf.ele.style.left = clientX - conf.offsetLeft + 'px'
        //   }
        //
        // } else if (conf.isDown) {
        //   // 鼠标移动量大于 5 时 移动状态生效
        //   conf.isMove = Math.abs(clientX - conf.clientX) > 5 || Math.abs(clientY - conf.clientY) > 5
        // }
      },
      docMouseup({clientX, clientY}) {
        // const conf = this.dragConf
        // conf.isDown = false
        //
        // if (conf.isMove) {
        //   const {
        //     top,
        //     right,
        //     bottom,
        //     left
        //   } = this.$refs.flowContainer.getBoundingClientRect()
        //
        //   // 判断鼠标是否进入 flow container
        //   if (
        //     clientX > left && clientX < right && clientY > top && clientY < bottom
        //   ) {
        //     // 获取拖动元素左上角相对 super flow 区域原点坐标
        //     const coordinate = this.$refs.superFlow.getMouseCoordinate(
        //       clientX - conf.offsetLeft,
        //       clientY - conf.offsetTop
        //     )
        //     // 添加节点
        //     this.$refs.superFlow.addNode({
        //       coordinate,
        //       ...conf.info
        //     })
        //   }
        //   conf.isMove = false
        // }
        // if (conf.ele) {
        //   conf.ele.remove()
        //   conf.ele = null
        // }
      },

    }
  }
</script>


<style>
  .demo-block-control {
    border: 1px solid #eaeefb;
    border-top: 0;
    height: 44px;
    line-height: 44px;
    box-sizing: border-box;
    background-color: #fafafa;
    border-bottom-left-radius: 4px;
    border-bottom-right-radius: 4px;
    text-align: center;
    margin-top: -1px;
    /*    color: #409EFF;*/
    cursor: pointer;
    position: relative;
  }

  .demo-block-control .dbsavebtn {
    visibility: hidden;
  }

  .demo-block-control:hover {
    background-color: #f4f7ff;
    color: #409aff;
  }

  .demo-block-control.hover {
    box-shadow: 0 0 8px 0 rgba(232, 237, 250, .6), 0 2px 4px 0 rgba(232, 237, 250, .5)
  }

  .demo-block-control:hover .dbsavebtn {
    visibility: visible;
  }

</style>